package com.fengba.nanzhi.fengba;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.myinfo.MyInfo;
import com.fengba.nanzhi.tabbar01.Tabbar01;
import com.fengba.nanzhi.tabbar02.Tabbar02;
import com.fengba.nanzhi.tabbar03.Tabbar03;
import com.fengba.nanzhi.tabbar04.Tabbar04;
import com.fengba.nanzhi.tabbar04.wz.FaceActivity;
import com.fengba.nanzhi.utils.Function;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener{

    private BottomNavigationBar bottomNavigationBar;
    int lastSelectedPosition = 0;
    private String tag = MainActivity.class.getSimpleName();
    private Tabbar01 tabbar01;
    private Tabbar02 tabbar02;
    private Tabbar03 tabbar03;
    private Tabbar04 tabbar04;
    /* 引导页 */
    private View guide01;
    private View guide02;
    private View guide03;
    private View guide04;
    private ViewPager viewPager;
    private ViewPagerIndicator vpAdapter;
    private ImageView viewpager_background;
    private List<View> viewList;

    /**
     *Activity创建或者从后台重新回到前台时被调用
     */
    @Override
    protected void onStart() {
        super.onStart();
        //LogUtils.e("onStart is invoke!!!");
    }

    /**
     * Activity从后台重新回到前台时被调用
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        todayLuckYou();
        if(tabbar04!=null){
            tabbar04.initData();
        }
    }

    /**
     *Activity创建或者从被覆盖、后台重新回到前台时被调用
     */
    @Override
    protected void onResume() {
        super.onResume();
        //Log.e("onResume","onResume is invoke!!!");
    }

    /**
     *  Activity被覆盖到下面或者锁屏时被调用
     */
    @Override
    protected void onPause() {
        super.onPause();
        //LogUtils.e("onPause is invoke!!!");
    }

    /**
     *退出当前Activity或者跳转到新Activity时被调用
     */
    @Override
    protected void onStop() {
        super.onStop();
        //LogUtils.e("onStop is invoke!!!");
    }

    /**
     *退出当前Activity时被调用,调用之后Activity就结束了
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //LogUtils.e("onDestroy is invoke!!!");
    }

    /**
     * Activity创建时被调用
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        todayLuckYou();

        /**
         * app通信返回的消息进行的跳转
         */
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if ( uri != null) {
            if(uri.getHost().equals("success")) {
                String mUri = uri.getQuery();
                try {
                    JSONObject myjson = new JSONObject(uri.getQueryParameter("biz_content"));
                    String biz_no = myjson.get("biz_no").toString();
                    Intent intent1 = new Intent(MainActivity.this, FaceActivity.class);
                    intent1.putExtra("biz_no",biz_no);
                    startActivity(intent1);
                }catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }

        /**
         * bottomNavigation 设置
         */
        bottomNavigationBar = (BottomNavigationBar)findViewById(R.id.bottom_navigation_bar);

        /** 导航基础设置 包括按钮选中效果 导航栏背景色等 */
        bottomNavigationBar
                .setTabSelectedListener(this)
                /**
                 *  setMode() 内的参数有三种模式类型：
                 *  MODE_DEFAULT 自动模式：导航栏Item的个数<=3 用 MODE_FIXED 模式，否则用 MODE_SHIFTING 模式
                 *  MODE_FIXED 固定模式：未选中的Item显示文字，无切换动画效果。
                 *  MODE_SHIFTING 切换模式：未选中的Item不显示文字，选中的显示文字，有切换动画效果。
                 */
                .setMode(BottomNavigationBar.MODE_FIXED)
                /**
                 *  setBackgroundStyle() 内的参数有三种样式
                 *  BACKGROUND_STYLE_DEFAULT: 默认样式 如果设置的Mode为MODE_FIXED，将使用BACKGROUND_STYLE_STATIC
                 *                                    如果Mode为MODE_SHIFTING将使用BACKGROUND_STYLE_RIPPLE。
                 *  BACKGROUND_STYLE_STATIC: 静态样式 点击无波纹效果
                 *  BACKGROUND_STYLE_RIPPLE: 波纹样式 点击有波纹效果
                 */
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC)
                .setActiveColor("#ff7200")//选中颜色
                .setInActiveColor("#999999")//未选中颜色
                .setBarBackgroundColor("#ffffff");//导航栏背景色

        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.mipmap.tabbar_0001,"疯啦"))
                .addItem(new BottomNavigationItem(R.mipmap.tabbar_0002,"战豆"))
                .addItem(new BottomNavigationItem(R.mipmap.tabbar_0003,"抽疯"))
                .addItem(new BottomNavigationItem(R.mipmap.tabbar_0004,"我的"))
                .initialise();

        setDefaultFragment();

        //引导页
        initGuide();
    }

    /**
     * 设置默认导航栏
     */
    private void setDefaultFragment(){
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transction = fm.beginTransaction();
        tabbar01 = Tabbar01.newInstance("疯吧");
        transction.replace(R.id.tb,tabbar01);
        transction.commit();
    }

    /**
     * 设置导航选中的事件
     */
    @Override
    public void onTabSelected(int position){
        //System.out.println("ccc");
        Log.d(tag,"onTabSelected() called with:"+"position = [" + position + "]");
        FragmentManager fm = this.getFragmentManager();
        //开启事物
        FragmentTransaction transaction = fm.beginTransaction();
        switch (position){
            case 0:
                if(tabbar01 == null){
                    tabbar01 = Tabbar01.newInstance("疯吧");
                }
                transaction.replace(R.id.tb,tabbar01);
                break;
            case 1:
                if(tabbar02 == null){
                    tabbar02 = Tabbar02.newInstance("战豆");
                }
                transaction.replace(R.id.tb,tabbar02);
                break;
            case 2:
                if(tabbar03 == null){
                    tabbar03 = Tabbar03.newInstance("抽疯");
                }
                transaction.replace(R.id.tb,tabbar03);
                break;
            case 3:
                if(tabbar04 == null){
                    tabbar04 = Tabbar04.newInstance("我的");
                }
                transaction.replace(R.id.tb,tabbar04);
                break;
            default:
                break;
        }
        transaction.commit();// 事务提交
    }

    /**
     *隐藏status状态栏
     */
    private void hideStatusBar(boolean isHide)
    {
        if (isHide)
        {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else
        {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            //如果不注释下面这句话，状态栏将把界面挤下去
            /*getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);*/
        }
    }


    /**
     * 设置未选中Fragment 事务
     */
    @Override
    public void onTabUnselected(int position) {

    }

    /**
     * 设置释放Fragment 事务
     */
    @Override
    public void onTabReselected(int position) {

    }

    /**
     * 每日登录
     */
    private void todayLuckYou(){
        Object user_info = Preferences.getParam(this,"user_info","");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());
            //id
            String id = myJson.get("id").toString();
            //账号
            Object account = Preferences.getParam(MainActivity.this,"account","");
            //密码
            Object password = Preferences.getParam(MainActivity.this,"password","");
            //registrationId
            String registrationId = "1000";
            //
            //Log.e("ii",id+"|"+account+"|"+password+"|"+registrationId);
            OKManager.getInstance().type0004(id, account.toString(), password.toString(), registrationId, new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        if(Integer.parseInt(jsonObject.get("code").toString()) == 0){
                            //获取data
                            JSONObject data = jsonObject.getJSONObject("data");
                            //保存数据
                            Preferences.clear(MainActivity.this,"user_info");
                            Preferences.setParam(MainActivity.this,"user_info",data.toString());
                            //Log.e("changeUserinfo",data.toString());

                            String message = jsonObject.get("message").toString();
                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();

                        }else if(Integer.parseInt(jsonObject.get("code").toString()) == 1){
                            JSONObject data = jsonObject.getJSONObject("data");
                            //保存数据
                            Preferences.clear(MainActivity.this,"user_info");
                            Preferences.setParam(MainActivity.this,"user_info",data.toString());
                            //Log.e("changeUserinfo",data.toString());

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String string) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 引导页
     */
    private void initGuide(){
        //是否第一次进入app
        Object first_main = Preferences.getParam(MainActivity.this,"first_main","");
        if(first_main.toString().equals("1")){
            RelativeLayout layout = (RelativeLayout) findViewById(R.id.viewpager_box);
            layout.setVisibility(View.INVISIBLE);
            return;
        }
        /**
         * 屏幕的宽高
         */
        int screenWidth = Function.getScreenWidth(this);
        int screenHeight = Function.getScreenHeight(this);
        int screenWidthDP = Function.getScreenWidthReturnDP(this);
        int screenHeightDP = Function.getScreenHeightReturnDP(this);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        LayoutInflater inflater=getLayoutInflater();
        guide01 = inflater.inflate(R.layout.dmy_guidepage01, null);
        guide02 = inflater.inflate(R.layout.dmy_guidepage02,null);
        guide03 = inflater.inflate(R.layout.dmy_guidepage03, null);
        guide04 = inflater.inflate(R.layout.dmy_guidepage04, null);

        viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
        viewList.add(guide01);
        viewList.add(guide02);
        viewList.add(guide03);
        viewList.add(guide04);

        //设置背景居中1125x2436
        viewpager_background = (ImageView) findViewById(R.id.viewpager_background);
        RelativeLayout.LayoutParams viewpager_background_params = new RelativeLayout.LayoutParams(0,0);
        viewpager_background_params.width = screenWidth;
        viewpager_background_params.height = screenWidth * (2436/1125);
        viewpager_background.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_01));
        viewpager_background.setLayoutParams(viewpager_background_params);
        //laytou01 544 × 345 778 × 621
        ImageView guide01_image01 = (ImageView) guide01.findViewById(R.id.guide01_image01);
        ImageView guide01_image02 = (ImageView) guide01.findViewById(R.id.guide01_image02);
        LinearLayout.LayoutParams guide01_image01_params = new LinearLayout.LayoutParams(0,0);
        guide01_image01_params.topMargin = Function.dip2px(this,60);
        guide01_image01_params.leftMargin = (int)(screenWidth * 0.1);
        guide01_image01_params.width = (int)(screenWidth * 0.8);
        guide01_image01_params.height = (int)(screenWidth * 0.8 * (345.0/544));
        guide01_image01.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_a_01));
        guide01_image01.setLayoutParams(guide01_image01_params);

        LinearLayout.LayoutParams guide01_image02_params = new LinearLayout.LayoutParams(0,0);
        guide01_image02_params.leftMargin = (int)(screenWidth * 0.1);
        guide01_image02_params.width = (int)(screenWidth * 0.8);
        guide01_image02_params.height = (int)(screenWidth * 0.8 * (621.0/778));
        guide01_image02.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_t_01));
        guide01_image02.setLayoutParams(guide01_image02_params);

        //laytou02 544 × 345 778 × 621
        ImageView guide02_image01 = (ImageView) guide02.findViewById(R.id.guide02_image01);
        ImageView guide02_image02 = (ImageView) guide02.findViewById(R.id.guide02_image02);
        LinearLayout.LayoutParams guide02_image01_params = new LinearLayout.LayoutParams(0,0);
        guide02_image01_params.topMargin = Function.dip2px(this,60);
        guide02_image01_params.leftMargin = (int)(screenWidth * 0.1);
        guide02_image01_params.width = (int)(screenWidth * 0.8);
        guide02_image01_params.height = (int)(screenWidth * 0.8 * (345.0/544));
        guide02_image01.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_a_02));
        guide02_image01.setLayoutParams(guide02_image01_params);

        LinearLayout.LayoutParams guide02_image02_params = new LinearLayout.LayoutParams(0,0);
        guide02_image02_params.leftMargin = (int)(screenWidth * 0.1);
        guide02_image02_params.width = (int)(screenWidth * 0.8);
        guide02_image02_params.height = (int)(screenWidth * 0.8 * (621.0/778));
        guide02_image02.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_t_02));
        guide02_image02.setLayoutParams(guide02_image02_params);

        //laytou03 544 × 345 778 × 621
        ImageView guide03_image01 = (ImageView) guide03.findViewById(R.id.guide03_image01);
        ImageView guide03_image02 = (ImageView) guide03.findViewById(R.id.guide03_image02);
        LinearLayout.LayoutParams guide03_image01_params = new LinearLayout.LayoutParams(0,0);
        guide03_image01_params.topMargin = Function.dip2px(this,60);
        guide03_image01_params.leftMargin = (int)(screenWidth * 0.1);
        guide03_image01_params.width = (int)(screenWidth * 0.8);
        guide03_image01_params.height = (int)(screenWidth * 0.8 * (345.0/544));
        guide03_image01.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_a_03));
        guide03_image01.setLayoutParams(guide03_image01_params);

        LinearLayout.LayoutParams guide03_image02_params = new LinearLayout.LayoutParams(0,0);
        guide03_image02_params.leftMargin = (int)(screenWidth * 0.1);
        guide03_image02_params.width = (int)(screenWidth * 0.8);
        guide03_image02_params.height = (int)(screenWidth * 0.8 * (621.0/778));
        guide03_image02.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_t_03));
        guide03_image02.setLayoutParams(guide03_image02_params);

        //laytou04 544 × 345 778 × 621
        ImageView guide04_image01 = (ImageView) guide04.findViewById(R.id.guide04_image01);
        ImageView guide04_image02 = (ImageView) guide04.findViewById(R.id.guide04_image02);
        Button switch_main = (Button) guide04.findViewById(R.id.switch_fengba);
        LinearLayout.LayoutParams guide04_image01_params = new LinearLayout.LayoutParams(0,0);
        guide04_image01_params.topMargin = Function.dip2px(this,60);
        guide04_image01_params.leftMargin = (int)(screenWidth * 0.1);
        guide04_image01_params.width = (int)(screenWidth * 0.8);
        guide04_image01_params.height = (int)(screenWidth * 0.8 * (345.0/544));
        guide04_image01.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_a_04));
        guide04_image01.setLayoutParams(guide04_image01_params);

        LinearLayout.LayoutParams guide04_image02_params = new LinearLayout.LayoutParams(0,0);
        guide04_image02_params.leftMargin = (int)(screenWidth * 0.1);
        guide04_image02_params.width = (int)(screenWidth * 0.8);
        guide04_image02_params.height = (int)(screenWidth * 0.8 * (621.0/778));
        guide04_image02.setBackground(ContextCompat.getDrawable(this,R.mipmap.guide_t_04));
        guide04_image02.setLayoutParams(guide04_image02_params);

        switch_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout layout = (RelativeLayout) findViewById(R.id.viewpager_box);
                layout.setVisibility(View.INVISIBLE);
                //第一次引导页
                Preferences.setParam(MainActivity.this,"first_main","1");
            }
        });

        //设置原点
        LinearLayout layout = (LinearLayout) findViewById(R.id.viewpager_layout);
        vpAdapter = new ViewPagerIndicator(this,viewPager,layout,4);
        viewPager.setAdapter(vpAdapter);
        //注册
        //viewPager.addOnPageChangeListener();
        //viewPager.setOnPageChangeListener(new ViewPagerIndicator(this, vpAdapter, layout, 4));



        PagerAdapter pagerAdapter = new PagerAdapter() {

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                // TODO Auto-generated method stub
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return viewList.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                // TODO Auto-generated method stub
                container.removeView(viewList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                // TODO Auto-generated method stub
                container.addView(viewList.get(position));


                return viewList.get(position);
            }
        };


        viewPager.setAdapter(pagerAdapter);

    }

}
